/**
 * Created by liqiao on 8/10/15.
 */

logger.i('Here we go...');

logger.i(location.href);

/**
 * _config comes from server-side template. see views/index.jade
 */
dd.config({
    agentId: _config.agentId,
    corpId: _config.corpId,
    timeStamp: _config.timeStamp,
    nonceStr: _config.nonceStr,
    signature: _config.signature,
    jsApiList: [
        'runtime.info',
        'device.notification.prompt',
        'biz.chat.pickConversation',
        'device.notification.confirm',
        'device.notification.alert',
        'device.notification.prompt',
        'biz.chat.open',
        'biz.util.open',
        'biz.user.get',
        'biz.contact.choose',
        'biz.telephone.call',
        'biz.util.uploadImage',
        'biz.ding.post']
});
dd.userid=0;
dd.ready(function() {
    logger.i('dd.ready rocks!');

    // 退到后台的事件监听(webview)
    document.addEventListener('pause', function(e) {
        e.preventDefault();
        console.log('事件：pause')
    }, false);

    // 页面被唤醒的事件监听(webview)
    document.addEventListener('resume', function(e) {
        e.preventDefault();
        console.log('事件：resume')
    }, false);

    //返回按钮点击的事件监听(android)
    document.addEventListener('backbutton', function(e) {
        e.preventDefault();
        dd.device.notification.alert({
            message: '哎呀，你不小心点到返回键啦!',
            title: '...警告...'
        });
    }, false);

    dd.runtime.info({
        onSuccess: function(info) {
            logger.i('runtime info: ' + JSON.stringify(info));
        },
        onFail: function(err) {
            logger.e('fail: ' + JSON.stringify(err));
        }
    });

    dd.runtime.permission.requestAuthCode({
        corpId: _config.corpId, //企业id
        onSuccess: function (info) {
            logger.i('authcode: ' + info.code);
            $.ajax({
                url: '/sendMsg.php',
                type:"POST",
                data: {"event":"get_userinfo","code":info.code,"corpId":_config.corpId},
                dataType:'json',
                timeout: 900,
                success: function (data, status, xhr) {
                    var info = JSON.parse(data);
                    if (info.errcode === 0) {
                        logger.i('user id: ' + info.userid);
                        dd.userid = info.userid;
                    }
                    else {
                        logger.e('auth error: ' + data);
                    }
                },
                error: function (xhr, errorType, error) {
                    logger.e(errorType + ', ' + error);
                }
            });
        },
        onFail: function (err) {
            logger.e('requestAuthCode fail: ' + JSON.stringify(err));
        }
    });

    $('.chooseonebtn').on('click', function() {

        dd.biz.chat.pickConversation({
            corpId: _config.corpId, //企业id
            isConfirm:'false', //是否弹出确认窗口，默认为true
            onSuccess: function (data) {
                var chatinfo = data;
                if(chatinfo){
                console.log(chatinfo.cid);
                    dd.device.notification.prompt({
                        message: "发送消息",
                        title: chatinfo.title,
                        buttonLabels: ['发送', '取消'],
                        onSuccess : function(result) {
                            var text = result.value;
                            if(text==''){
                                return false;
                            }

                            $.ajax({
                                url: '/sendMsg.php',
                                type:"POST",
                                data: {"event":"send_to_conversation","cid":chatinfo.cid,"sender":dd.userid,"content":text,"corpId":_config.corpId},
                                dataType:'json',
                                timeout: 900,
                                success: function (data, status, xhr) {
                                    var info = data;
                                    logger.i('sendMsg: ' + JSON.stringify(data));
                                    if(info.errcode==0){
                                        logger.i('sendMsg: 发送成功');
                                        /**
                                         * 跳转到对话界面
                                         */
                                        dd.biz.chat.open({
                                            cid:chatinfo.cid,
                                            onSuccess : function(result) {
                                            },
                                            onFail : function(err) {}
                                        });
                                    }else{
                                        logger.e('sendMsg: 发送失败'+info.errmsg);
                                    }
                                },
                                error: function (xhr, errorType, error) {
                                    logger.e(errorType + ', ' + error);
                                }
                            });
                        },
                        onFail : function(err) {}
                    });
                }
            },
            onFail: function (err) {
            }
        });
    });

    $('.phonecall').on('click', function() {
        dd.biz.contact.choose({
            startWithDepartmentId: 0, //-1表示打开的通讯录从自己所在部门开始展示, 0表示从企业最上层开始，(其他数字表示从该部门开始:暂时不支持)
            multiple: false, //是否多选： true多选 false单选； 默认true
            users: [], //默认选中的用户列表，userid；成功回调中应包含该信息
            corpId: _config.corpId, //企业id
            max: 10, //人数限制，当multiple为true才生效，可选范围1-1500
            onSuccess: function(data) {
                if(data&&data.length>0){
                    var selectUserId = data[0].emplId;
                    if(selectUserId>0){
                        dd.biz.telephone.call({
                            users: [selectUserId], //用户列表，工号
                            corpId: _config.corpId, //企业id
                            onSuccess : function(info) {
                                logger.i('biz.telephone.call: info' + JSON.stringify(info));

                            },
                            onFail : function(err) {
                                logger.e('biz.telephone.call: error' + JSON.stringify(err));
                            }
                        })
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
        },
        onFail : function(err) {}
    });
    });

    $('.previewdpan').on('click',function() {
        dd.biz.cspace.preview({
            corpId:_config.corpId,
            spaceId:"13557022",
            fileId:"11452819",
            fileName:"钉盘快速入门.pdf",
            fileSize:1024,
            fileType:"pdf",
            onSuccess: function() {
                //无，直接在native显示文件详细信息
            },
            onFail: function(err) {
                // 无，直接在native页面显示具体的错误
            }
        });
    });

    //转存文件到钉盘
    $('.savedpan').on('click',function () {
        //获取企业下的自定义空间
        $.ajax({
            url: '/sendMsg.php',
            type:"POST",
            data: {"event":"get_custom_space","corpId":_config.corpId},
            dataType:'json',
            timeout: 900,
            success: function (data, status, xhr) {
                var info = data;
                if (info.errcode === 0) {
                    logger.i('spaceid: ' + info.spaceid);
                }
                else {
                    logger.e('auth error: ' + data);
                }
            },
            error: function (xhr, errorType, error) {
                logger.e(errorType + ', ' + error);
            }
        });
        // $.ajax({
        //     url: '/sendMsg.php',
        //     type:"POST",
        //     data: {"event":"grant_custom_space","corpId":_config.corpId,"userid":"manager4683"},
        //     dataType:'json',
        //     timeout:900,
        //     success: function (data, status, xhr) {
        //         var info = data;
        //         alert(info);
        //         if(info.errcode === 0) {
        //             logger.i(info.errmsg);
        //         }
        //     }
        // });
        // dd.biz.cspace.saveFile({
        //     corpId:_config.corpId,
        //     url:"https://www.xaqtj.com/public/test.pdf",
        //     name:"钉钉测试文件",
        //     onSuccess: function(data) {
        //         /* data结构
        //         {"data":
        //            [
        //            {
        //            "corpId": "", //公司id
        //            "spaceId": "" //空间id
        //            "fileId": "", //文件id
        //            "fileName": "", //文件名
        //            "fileSize": 111111, //文件大小
        //            "fileType": "", //文件类型
        //            }
        //            ]
        //         }
        //         */
        //         alert("data:" + JSON.stringify(data));
        //     },
        //     onFail: function(err) {
        //         alert(JSON.stringify(err));
        //     }
        // });
    })

    //上传附件
    $('.uploadAttachment').on('click',function () {
        dd.biz.util.uploadAttachment({
            image:{multiple:true,compress:false,max:9,spaceId: "12345"},
            space:{corpId:_config.corpId,spaceId:"12345",isCopy:1 , max:9},
            file:{spaceId:"12345",max:1},
            types:["photo","camera","file","space"],
            onSuccess : function(result) {
                //onSuccess将在文件上传成功之后调用
                /*
               {
                  type:'', // 用户选择了哪种文件类型 ，image（图片）、file（手机文件）、space（钉盘文件）
                  data: [
                     {
                       spaceId: "232323",
                       fileId: "DzzzzzzNqZY",
                       fileName: "审批流程.docx",
                       fileSize: 1024,
                       fileType: "docx"
                    },
                    {
                       spaceId: "232323",
                       fileId: "DzzzzzzNqZY",
                       fileName: "审批流程1.pdf",
                       fileSize: 1024,
                       fileType: "pdf"
                    },
                    {
                       spaceId: "232323",
                       fileId: "DzzzzzzNqZY",
                       fileName: "审批流程3.pptx",
                       fileSize: 1024,
                       fileType: "pptx"
                     }
                  ]

               }
                */
            },
            onFail : function(err) {}
        });
    })

});

dd.error(function(err) {
    /**
     *  message:"错误信息",//message信息会展示出钉钉服务端生成签名使用的参数，请和您生成签名的参数作对比，找出错误的参数
     *  errorCode:"错误码"
     */
    logger.e('dd error: ' + JSON.stringify(err));
});
